package com.quectel.core.module.device.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.quectel.constant.global.SystemConstants;
import com.quectel.core.constants.RedisCacheConstants;
import com.quectel.core.module.device.dao.DeviceOn3dDao;
import com.quectel.core.module.device.dto.DeviceOn3dDto;
import com.quectel.core.module.device.entity.DeviceOn3dEntity;
import com.quectel.core.module.device.service.DeviceOn3dService;
import com.quectel.core.module.device.service.DeviceService;
import com.quectel.core.module.village.dto.VillageDto;
import com.quectel.core.module.village.service.VillageService;
import com.quectel.util.common.CopyUtils;
import com.quectel.util.kit.CacheKit;
import com.quectel.util.kit.Snowflake;
import com.quectel.util.mybatis.MyBatisPlusUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.dubbo.config.annotation.DubboService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
import java.util.function.Function;

/**
 * @author caolu
 * @email louis.cao@quectel.com
 * @date 2023/03/24 09:31
 */
@DubboService
public class DeviceOn3dServiceImpl extends ServiceImpl<DeviceOn3dDao, DeviceOn3dEntity> implements DeviceOn3dService {

    private static final Logger LOGGER = LoggerFactory.getLogger(DeviceOn3dServiceImpl.class);

    /**
     * 入参解释:实体id
     */
    private static final Function<Long, String> DEVICE_ON_3D_CACHE_BY_ID_FUNC = id -> String.format(RedisCacheConstants.PROJECT_NAME + "DEVICE_ON_3D_CACHE_BY_ID:%d", id);

    /**
     * 清除缓存方法
     */
    private static final Consumer<DeviceOn3dDto> CLEAR_CACHE_FUNC = dto -> {
        CacheKit.invalidRedisCache(DEVICE_ON_3D_CACHE_BY_ID_FUNC.apply(dto.getId()));
    };

    @Autowired
    private DeviceOn3dDao deviceOn3dDao;
    @Autowired
    private DeviceService deviceService;
    @Autowired
    private VillageService villageService;


    @Override
    public void batchSave(Long villageId, List<DeviceOn3dDto> list) {
        if (CollectionUtils.isEmpty(list)) {
            return;
        }
        // 查询小区根据索引加快速度
        VillageDto villageDto = villageService.selectCacheById(villageId);
        if (villageDto == null) {
            return;
        }
        deviceOn3dDao.delete(new LambdaQueryWrapper<DeviceOn3dEntity>()
                .eq(DeviceOn3dEntity::getTenantId, villageDto.getTenantId())
                .eq(DeviceOn3dEntity::getVillageId, villageId)
        );

        List<DeviceOn3dEntity> entityList = CopyUtils.copyList(list, DeviceOn3dEntity.class);
        entityList.forEach(v -> {
            v.setId(Snowflake.nextId());
            v.setTenantId(villageDto.getTenantId());
        });

        super.saveBatch(entityList);

    }

    @Override
    public DeviceOn3dDto selectCacheById(Long id) {
        return CacheKit.cacheToRedis(
                () -> selectById(id),
                DEVICE_ON_3D_CACHE_BY_ID_FUNC.apply(id),
                SystemConstants.NOT_NULL_CACHE_EXPIRE_SECONDS
        );
    }

    @Override
    public DeviceOn3dDto selectById(Long id) {
        DeviceOn3dEntity entity = deviceOn3dDao.selectById(id);
        return paddingField(CopyUtils.copyObj(entity, DeviceOn3dDto.class));
    }

    @Override
    public List<DeviceOn3dDto> queryList(Map<String, Object> params) {
        List<DeviceOn3dEntity> list = deviceOn3dDao.queryList(params);
        List<DeviceOn3dDto> result = CopyUtils.copyList(list, DeviceOn3dDto.class);
        result.forEach(this::paddingField);
        return result;
    }

    /**
     * 此方法慎用 禁止填充List一类 比如一个人有多个地址这里不允许填充
     * 填充的原则是: 1:被填充对象不经常变换 2:根据id可以走缓存 3数据足够简单 比如设备类型 所属园区等
     *
     * @param dto
     * @return
     */
    private DeviceOn3dDto paddingField(DeviceOn3dDto dto) {
        if (dto != null) {
            dto.setDeviceDto(deviceService.selectById(dto.getDeviceId()));
        }
        return dto;
    }

    @Override
    public int queryTotal(Map<String, Object> params) {
        return deviceOn3dDao.queryTotal(params);
    }

    @Override
    public Long save(DeviceOn3dDto dto) {
        DeviceOn3dEntity entity = CopyUtils.copyObj(dto, DeviceOn3dEntity.class);
        entity.setId(Snowflake.nextId());
        deviceOn3dDao.insert(entity);
        return entity.getId();
    }

    @Override
    public void updateById(DeviceOn3dDto dto) {
        DeviceOn3dEntity entity = CopyUtils.copyObj(dto, DeviceOn3dEntity.class);

        deviceOn3dDao.updateById(entity);

        CLEAR_CACHE_FUNC.accept(dto);
    }

    @Override
    public void updateAllColumnById(DeviceOn3dDto dto) {
        DeviceOn3dEntity entity = CopyUtils.copyObj(dto, DeviceOn3dEntity.class);

        MyBatisPlusUtils.updateAllColumnById(entity, deviceOn3dDao);

        CLEAR_CACHE_FUNC.accept(dto);
    }

    @Override
    public void deleteById(Long id) {

        CLEAR_CACHE_FUNC.accept(selectById(id));

        deviceOn3dDao.deleteById(id);

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteBatch(Long[] ids) {
        for (Long id : ids) {
            deleteById(id);
        }
    }
}
